﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using S7.Net;
using thinger.HeatingControlProject._1.界面层;
using thinger.HeatingControlProject._2.数据层;
using thinger.HeatingControlProject._4.实体类;

namespace thinger.HeatingControlProject
{
    public partial class FrmMain : Form
    {
        #region 无边框拖动 

        private Point mPoint;
        private void Panel_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new Point(e.X, e.Y);
        }

        private void Panel_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
            }
        }
        #endregion
        public FrmMain()
        {
            InitializeComponent();
            //显示当前登录用户名
            this.lblCurrentAdmin.Text = Program.currentAdmin.LoginName;
        }

        Plc plc = null;//声明PLC通信类
        private PlcInfo plcInfo = new PlcInfo();
        private PlcInfoService infoService = new PlcInfoService();
        private string path = Application.StartupPath + "//PLCInfo.ini";



        private void btn_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(MessageBox.Show("确定退出么？","询问退出",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
        }

        //系统启动

        private PLCDataService dataService = new PLCDataService();
        private void btn_SystemStart_Click(object sender, EventArgs e)
        {
            try
            {
                dataService.Connect(this.plcInfo);
                this.led_PLCState.LedState = 1;

                this.btn_SystemStart.Enabled = false;
                this.btn_SystemStop.Enabled = true;

                this.readTimer.Start();

            }
            catch (Exception ex)
            {

                MessageBox.Show("系统启动失败！原因：" + ex.Message, "启动提示");
                
            }

        }

        private void btn_ParamSet_Click(object sender, EventArgs e)
        {
            FrmParamSet frm = new FrmParamSet(this.plcInfo,this.path);
            frm.ShowDialog(); 
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                this.plcInfo = infoService.GetPlcInfoByPath(path);
                if(this.plcInfo == null)
                {
                    MessageBox.Show("配置信息文件不存在,请配置！","信息提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("PLC配置信息加载失败" + ex.Message, "读取配置");
            }
        }
        //系统停止
        private void btn_SystemStop_Click(object sender, EventArgs e)
        {
            this.readTimer.Stop();//先停止定时器
            dataService.Disconnect();
            this.led_PLCState.LedState= 0;
            this.btn_SystemStart.Enabled = true;
            this.btn_SystemStop.Enabled = false;
        }

        private void UpdateUI(PLCData data)
        {
            //各种泵和阀门状态
            this.pump_FeedState.IsRun = data.FeedPumpState;
            this.pump_AddState.IsRun = data.AddPumpState;
            this.pump_AirState.IsRun = data.AirPumpState;
            this.pump_CircleState.PumpState = data.CirclePumpState?1:0;
            this.valve_OutState.IsOpen = data.OutValveState;
            this.led_SystemState.LedState = data.SystemState?1:0;
            //数据显示
            this.lbl_TempIn.Text = data.TempIn.ToString("F1");//保留一位小数
            this.lbl_TempOut.Text = data.TempOut.ToString("F1");
            this.lbl_PressureBoiler.Text = data.PressureBoiler.ToString("F1");
            this.lbl_PressureIn.Text = data.PressureIn.ToString("F1") + "Bar";
            this.lbl_TempIn2.Text = data.TempIn.ToString("F1") + "℃";
            this.lbl_TempOut2.Text = data.TempOut.ToString("F1")+ "℃";
            this.lbl_PressureOut.Text = data.PressureOut.ToString("F1") + "Bar";
            this.lbl_LevelTank.Text = data.LevelTank.ToString("F1") + "%";
            this.lbl_TempBoiler.Text = data.TempBoiler.ToString("F1") + "℃";
            this.lbl_LevelBoiler.Text = data.LevelBoiler.ToString("F1") + "%";
            this.lbl_PressureBoiler2.Text = data.PressureOut.ToString("F1") + "Bar";
            //仪表显示
            this.meter_PressureIn.Value = data.PressureIn;
            this.meter_TempIn.Value = data.TempIn;
            this.meter_TempOut.Value = data.TempOut;
            this.meter_PressureOut.Value = data.PressureOut;
            this.meter_LevelTank.Value = data.LevelTank;
            this.meter_TempBoiler.Value = data.TempBoiler;
            this.meter_LevelBoiler.Value = data.LevelBoiler;
            this.meter_PressureBoiler.Value = data.PressureBoiler;
            //液位显示
            this.wave_LevelTank.Value = (int)data.LevelTank;
            this.ct_boiler.BoilerLevel = data.LevelBoiler;


        }

        private DateTime lastTimer = DateTime.Now;
        private SqlDataService sqlDataService = new SqlDataService();
        private void readTimer_Tick(object sender, EventArgs e)
        {
            //显示数据
            try
            {
                PLCData plcData = dataService.GetPLCData();
                UpdateUI(plcData);

                int timespan = DateTime.Now.Second - lastTimer.Second;
                if (timespan == 1 || timespan == -59)
                {
                    sqlDataService.AddPLCData(plcData);//保存到数据库

                }
                lastTimer = DateTime.Now;
            }
            catch (Exception ex)
            {

                this.readTimer.Stop();
                MessageBox.Show("读取数据中断：" + ex.Message, "错误提示");
            }

        }

        //进水泵控制
        private void toggle_FeedPump_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                dataService.FeedPumpControl(this.toggle_FeedPump.Checked);
            }
            catch (Exception ex)
            {
                //关闭CheckedChanged事件
                this.toggle_FeedPump.CheckedChanged -= toggle_FeedPump_CheckedChanged;
                //恢复按钮的初始状态
                this.toggle_FeedPump.Checked = !this.toggle_FeedPump.Checked;
                //重新关联CheckChanged事件
                this.toggle_FeedPump.CheckedChanged += toggle_FeedPump_CheckedChanged;
                MessageBox.Show("进水泵控制失败，原因：" + ex.Message);
            }
        }

        //加水泵控制
        private void toggle_AddPump_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                dataService.AddPumpControl(this.toggle_AddPump.Checked);
            }
            catch (Exception ex)
            {
                //关闭CheckedChanged事件
                this.toggle_AddPump.CheckedChanged -= toggle_AddPump_CheckedChanged;
                //恢复按钮的初始状态
                this.toggle_AddPump.Checked = !this.toggle_AddPump.Checked;
                //重新关联CheckChanged事件
                this.toggle_AddPump.CheckedChanged += toggle_AddPump_CheckedChanged;
                MessageBox.Show("加水泵控制失败，原因：" + ex.Message);
            }
        }

        //燃气泵控制
        private void toggle_AirPump_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                dataService.AirPumpControl(this.toggle_AirPump.Checked);
            }
            catch (Exception ex)
            {
                //关闭CheckedChanged事件
                this.toggle_AirPump.CheckedChanged -= toggle_AirPump_CheckedChanged;
                //恢复按钮的初始状态
                this.toggle_AirPump.Checked = !this.toggle_AirPump.Checked;
                //重新关联CheckChanged事件
                this.toggle_AirPump.CheckedChanged += toggle_AirPump_CheckedChanged;
                MessageBox.Show("燃气泵控制失败，原因：" + ex.Message);
            }
        }

        //循环泵控制
        private void toggle_CirclePump_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                dataService.CirclePumpControl(this.toggle_CirclePump.Checked);
            }
            catch (Exception ex)
            {
                //关闭CheckedChanged事件
                this.toggle_CirclePump.CheckedChanged -= toggle_CirclePump_CheckedChanged;
                //恢复按钮的初始状态
                this.toggle_CirclePump.Checked = !this.toggle_CirclePump.Checked;
                //重新关联CheckChanged事件
                this.toggle_CirclePump.CheckedChanged += toggle_CirclePump_CheckedChanged;
                MessageBox.Show("循环泵控制失败，原因：" + ex.Message);
            }
        }

        //出水阀门控制
        private void lbl_ValveCtl_DoubleClick(object sender, EventArgs e)
        {
            string msg = lbl_ValveCtl.Text == "已关闭"?"打开":"关闭";
            DialogResult result = MessageBox.Show("确定要"+msg+"出水阀门吗？","阀门操作",MessageBoxButtons.OKCancel);
            if (result == DialogResult.OK)
            {
                try
                {
                    bool value = lbl_ValveCtl.Text == "已关闭" ? true : false;
                    dataService.OutValvePumpControl(value);
                    if(lbl_ValveCtl.Text == "已关闭")
                    {
                        this.lbl_ValveCtl.Text = "已打开";
                        this.lbl_ValveCtl.BackColor = System.Drawing.SystemColors.Highlight;
                    }
                    else
                    {
                        this.lbl_ValveCtl.Text = "已关闭";
                        this.lbl_ValveCtl.BackColor = Color.DarkOrange;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("出水阀门控制失败，原因：" + ex.Message);
                }
            }
        }

        private void btn_UserManage_Click(object sender, EventArgs e)
        {
            FrmUserManage frm = new FrmUserManage();
            frm.ShowDialog();
        }
        
        private void btn_History_Click(object sender, EventArgs e)
        {
            FrmHistoryQuery query = new FrmHistoryQuery();
            query.ShowDialog();
        }
    }
}
